package threads;

import java.util.logging.Level;

import model.Player;
import model.Preference;
import model.Settings;
import net.HttpRequestFacade;
import platform.PlatformObjectFactory;
import util.EmailSending;
import util.LoggingUtils;

public class PlayerThread implements Runnable {

	private Player	model;
	private boolean	stop;
	//RBB
	protected final String className = this.getClass().getName();

	public PlayerThread(Player player) {
		this.model = player;
		this.stop = false;
	}

	@Override
	public void run() {
		String classMethod = className + ".run()";
		LoggingUtils.logStart(classMethod + " which should run indefinitely");
		try {
			while (!this.stop) {
				if (this.model.isUpdated()) {
					Thread.yield();
				} else if (!this.model.play()) {
				} else {
				}
			}
			LoggingUtils.logEnd(classMethod);
		} catch (Exception e) {
			e.printStackTrace();
			
			LoggingUtils.log(Level.SEVERE, "restarting player since an exception occured in " + classMethod,e);
			
			HttpRequestFacade.postPlayerException("Critical", classMethod+"\n"+EmailSending.FormatException(e),"Restart");
			
			// Mailing the error 
			String EmailBody = EmailSending.ProcessEmailBody(e.getMessage(), "restarting player since an exception occured in "+classMethod, EmailSending.FormatException(e));
						
			util.EmailSending.getInstance().send(Settings.TO_USER, "Restarting:PlayerThread:" +
					"BoxID="+Preference.getInstance().getBoxID(), EmailBody);
			
			System.out.println("restarting player since an exception occured");
			PlatformObjectFactory.getInstance().getCommandExecutor().restartPlayer();
		}
		catch(Error er)
		{
			LoggingUtils.log(Level.SEVERE, "restarting player since an exception occured in " + classMethod,er);
			
			HttpRequestFacade.postPlayerException("Critical", classMethod+"\n"+EmailSending.FormatException(er),"Restart");
			
			// Mailing the error 
			String EmailBody = EmailSending.ProcessEmailBody(er.getMessage(), "restarting player since an exception occured in "+classMethod, EmailSending.FormatException(er));
						
			util.EmailSending.getInstance().send(Settings.TO_USER, "Restarting:PlayerThread:" +
					"BoxID="+Preference.getInstance().getBoxID(), EmailBody);
			
			System.out.println("restarting player since an exception occured");
			PlatformObjectFactory.getInstance().getCommandExecutor().restartPlayer();
		}
	}

	public void setStop(boolean stop) {
		this.stop = stop;
	}
}
